package com.wy.tranFile.controller;

import com.wy.tranFile.pojo.FileInfo;
import com.wy.tranFile.bean.FileMap;
import com.wy.tranFile.pojo.Result;
import com.wy.tranFile.service.TranFileService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.net.URLEncoder;

/**
 * @author 吴宇~
 * @motto 我亦无他，唯手熟尔。
 * @edition jdk1.8
 * @reflection 0-1 喧闹任其喧闹，自由我自为之，我自风情万种，与世无争。
 * @date 2023/06/16/23:10
 * @target 心若有所向往，何惧道阻且长
 */
@Controller
@RequestMapping("/index")
@CrossOrigin("*")
public class TranFileController {

    @Autowired
    private TranFileService tranFileService;
    @Autowired
    private FileMap fileMap;

    @PostMapping("/upload")
    @ResponseBody
    public Result upload(@RequestParam("file") MultipartFile multipartFile) throws Exception {
        Result result;
        if (multipartFile != null) {
            result = tranFileService.uploadFile(multipartFile);
        } else {
            result = Result.fail();
        }
        return result;
    }

    @GetMapping("/down/{fileId}")
    public ResponseEntity<byte[]> down(@PathVariable("fileId") String id) throws Exception {
        byte[] bytes = tranFileService.down(id);
        if (bytes != null) {
            FileInfo fileInfo = fileMap.get(id);
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.TEXT_PLAIN);
            ResponseEntity<byte[]> body = ResponseEntity.ok()
                    .contentType(MediaType.APPLICATION_OCTET_STREAM)
                    .headers(headers)
                    .header("Content-Disposition", "attachment; filename=\"" + URLEncoder.encode(fileInfo.getFileName(), "UTF-8") + "\"")
                    .body(bytes);
            return body;
        }
        // 如果byte数组为空，返回一个包含错误信息的ResponseEntity对象
        String errorMessage = "File byte array is empty for id: " + id;
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.TEXT_PLAIN);
        return new ResponseEntity<>(errorMessage.getBytes(), headers, HttpStatus.INTERNAL_SERVER_ERROR);
    }


    @PostMapping("test")
    @ResponseBody
    public String test() {
        return "success";
    }
}


/**
 * 1.做一个前端页面，可以上传与下载文件。用于无微信的网络传输。
 * <p>
 * 优化一下返回值。  大文件的任务先摆这儿， 啥时候再说，
 * <p>
 * 项目启动的预热搞一下、
 */
